package com.paas.form.service.impl;


import com.alibaba.fastjson.JSON;
import com.bpm.feign.model.ProcessCmd;
import com.bpm.feign.service.IBpmProcessInstanceService;
import com.paas.common.model.BaseUserInfo;
import com.paas.common.model.DataBaseEntity;
import com.paas.common.model.RestResponse;
import com.paas.common.model.ResultMessage;
import com.paas.common.util.BeanUtil;
import com.paas.common.util.ListUtil;
import com.paas.common.util.StringUtil;
import com.paas.common.util.UniqueIdUtil;
import com.paas.form.constant.FormConstant;
import com.paas.form.dto.FormViewPubChangeDto;
import com.paas.form.entity.*;
import com.paas.form.service.*;
import com.paas.form.vo.ChangeField;
import com.paas.form.vo.FormViewChangeInfoDetailVo;
import com.paas.plus.tool.form.model.View;
import com.paas.tool.entity.coderule.ToolsCodeRulesEntity;
import com.paas.tool.entity.desensitization.ToolDesensitizationRulesEntity;
import com.paas.tool.entity.validate.ToolValidateConfigEntity;
import com.paas.tool.feign.service.IMdmCodeRuleService;
import com.paas.tool.feign.service.IMdmToolDesensitizationRulesService;
import com.paas.tool.feign.service.IMdmToolValidateConfigService;
import com.publics.entity.UcDataBaseEntity;
import com.publics.entity.UcDictEntity;
import com.publics.feign.service.IDictService;
import com.publics.feign.service.IUcDataBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 视图变更业务接口
 */
@Slf4j
@Service("viewChangeService")
public class ViewChangeServiceImpl extends AbsChangeService implements IViewChangeService {


    @Autowired
    private IFormViewPubService formViewPubService;

    @Autowired
    public IFormViewService formViewService;

    @Autowired
    public IDictService dictService;

    @Autowired
    private IFormAttributePubService formAttributePubService;

    @Autowired
    public IMdmCodeRuleService codeRuleService;

    @Autowired
    private IFormViewChangeInfoService formViewChangeInfoService;

    @Autowired
    private IFormViewChangeInfoDetailService formViewChangeInfoDetailService;

    @Autowired
    public IBpmProcessInstanceService bpmProcessInstanceService;

    @Autowired
    public IMdmToolValidateConfigService mdmToolValidateConfigService;

    @Autowired
    public IMdmToolDesensitizationRulesService mdmToolDesensitizationRulesService;

    @Autowired
    public IUcDataBaseService ucDataBaseService;

    @Autowired
    public IFormDefinitionService formDefinitionService;


    public static final String CHANGE_VIEW_INFO = "form_view_pub";        //定版视图信息

    public static final String CHANGE_ATTR_INFO = "form_attribute_pub"; //视图属性信息

    /**
     * 定版视图变更，支持基本信息 属性信息的变更
     *
     * @param formViewPubChangeDto
     * @return
     */
    @Override
    public RestResponse saveViewPubChangeInfo(FormViewPubChangeDto formViewPubChangeDto, ProcessCmd processCmd, BaseUserInfo baseUserInfo) {
        //需要变更的视图信息
        FormViewPubEntity viewPubInfo = formViewPubChangeDto.getViewPubInfo();
        if (BeanUtil.isEmpty(viewPubInfo) || StringUtil.isEmpty(viewPubInfo.getId())) {
            return RestResponse.error("请求参数错误，视图对象为空");
        }

        /**
         * 检查是否存在变更中的视图信息
         */
        boolean flag;
        if (StringUtil.isEmpty(formViewPubChangeDto.getLogId())) {
            flag = formViewChangeInfoService.isExistsChange(FormConstant.ChangeTypeEnum.VIEW_CHANGE_TYPE.getType(), viewPubInfo.getId());
        } else {
            flag = formViewChangeInfoService.isExistsChange(FormConstant.ChangeTypeEnum.VIEW_CHANGE_TYPE.getType(), viewPubInfo.getId(), formViewPubChangeDto.getLogId());
        }
        if (flag) {
            return RestResponse.error("当前定版视图存在审批中的数据，请先审批之前的数据再发起变更！");
        }
        //查询变更前的视图信息
        FormViewPubEntity exsistsFormViewPubEntity = formViewPubService.getById(viewPubInfo.getId());

        //定义 变更前的视图属性信息
        Map<String, FormAttributePubEntity> existsAttributePubMap = new HashMap<String, FormAttributePubEntity>();
        List<FormAttributePubEntity> exsistsFormAttributePubList = formAttributePubService.getValidListByViewId(viewPubInfo.getId());
        if (BeanUtil.isNotEmpty(exsistsFormAttributePubList)) {
            existsAttributePubMap = exsistsFormAttributePubList.stream().collect(Collectors.toMap(FormAttributePubEntity::getId, item -> item));
        }

        //记录变更明细集合
        List<FormViewChangeInfoDetailEntity> detailList = new ArrayList<>();
        try {
            //对比视图基本信息
            compareChangeInfo(exsistsFormViewPubEntity, viewPubInfo, exsistsFormViewPubEntity.getId(), CHANGE_VIEW_INFO, detailList);

        } catch (Exception e) {
            throw new RuntimeException("设置视图基本信息变更项失败!" + e.getMessage());
        }
        //记录本次新增的属性
        List<FormAttributePubEntity> addFormAttributePubList = new ArrayList<>();
        //视图属性不为空
        if (BeanUtil.isNotEmpty(formViewPubChangeDto.getAttributePubList())) {
            for (FormAttributePubEntity formAttributePubEntity : formViewPubChangeDto.getAttributePubList()) {
                if (StringUtil.isNotEmpty(formAttributePubEntity.getId()) && existsAttributePubMap.containsKey(formAttributePubEntity.getId())) {
                    //修改项
                    //获取变更前的属性信息
                    FormAttributePubEntity prevFormAttributePub = existsAttributePubMap.get(formAttributePubEntity.getId());
                    try {
                        //对比属性变更信息
                        compareChangeInfo(prevFormAttributePub, formAttributePubEntity, prevFormAttributePub.getId(), CHANGE_ATTR_INFO, detailList);
                    } catch (Exception e) {
                        throw new RuntimeException("设置视图基本信息变更项失败!" + e.getMessage());
                    }
                    //对比结束移除
                    existsAttributePubMap.remove(formAttributePubEntity.getId());
                } else {
                    //新增项
                    FormAttributePubEntity addFormAttributePubEntity = new FormAttributePubEntity();
                    //复制属性
                    BeanUtil.copyProperties(addFormAttributePubEntity, formAttributePubEntity);
                    addFormAttributePubEntity.setId(UniqueIdUtil.getGuid());
                    //未审批通过的属性 状态为无效状态且不关联视图信息
                    addFormAttributePubEntity.setStatus("0");
                    addFormAttributePubEntity.setViewId(null);
                    addFormAttributePubList.add(addFormAttributePubEntity);
                    //添加新增属性信息至变更记录表中
                    addOrDelChangeDetail("A", addFormAttributePubEntity.getId(), CHANGE_ATTR_INFO, "新增属性", detailList);
                }
            }
        }

        /**
         * 获取删除的属性信息
         */
        if (existsAttributePubMap != null && existsAttributePubMap.size() > 0) {
            for (FormAttributePubEntity formAttributePubEntity : existsAttributePubMap.values()) {
                //记录删除的属性对象只变更记录表中
                addOrDelChangeDetail("D", formAttributePubEntity.getId(), CHANGE_ATTR_INFO, "删除属性", detailList);
            }
        }
        //变更项为空是直接返回
        if (detailList.size() == 0) {
            return RestResponse.error("没有存在变更项，不允许提交！");
        }
        FormViewChangeInfoEntity formViewChangeInfoEntity = new FormViewChangeInfoEntity();

        //驳回修改时 处理之前保存的业务数据
        if (StringUtil.isNotEmpty(formViewPubChangeDto.getLogId())) {
            //删除上次的变更明细
            formViewChangeInfoDetailService.deleteByChangeId(formViewPubChangeDto.getLogId());
        }

        FormViewPubEntity formViewPubBean = formViewPubService.getById(exsistsFormViewPubEntity.getId());

        FormViewPubEntity updateFormViewPubEntity = new FormViewPubEntity();
        updateFormViewPubEntity.setId(exsistsFormViewPubEntity.getId());
        if(StringUtil.isNotEmpty(formViewPubBean.getBizStatus())){
            if("50".equals(formViewPubBean.getBizStatus()) ||"35".equals(formViewPubBean.getBizStatus()) ||"45".equals(formViewPubBean.getBizStatus())){
                updateFormViewPubEntity.setBizStatus("35");
            }else {
                updateFormViewPubEntity.setBizStatus("30");
            }
        }else {
            updateFormViewPubEntity.setBizStatus("30");
        }
        formViewPubService.updateById(updateFormViewPubEntity);

        //设置变更主表基本信息
        if (StringUtil.isEmpty(formViewPubChangeDto.getLogId())) {
            formViewChangeInfoEntity.setId(UniqueIdUtil.getGuid());
            formViewChangeInfoEntity.setName(viewPubInfo.getName());
            formViewChangeInfoEntity.setLinkId(viewPubInfo.getId());
            formViewChangeInfoEntity.setOperationStatus(FormConstant.CHANGE_OPERATION_APPROVAL);
            formViewChangeInfoEntity.setType(FormConstant.ChangeTypeEnum.VIEW_CHANGE_TYPE.getType());
            formViewChangeInfoEntity.setRemark(formViewPubChangeDto.getRemark());
            formViewChangeInfoEntity.setChangeCount(String.valueOf(detailList.size()));
            formViewChangeInfoEntity.setStatus("1");
            //保存数据
            formViewChangeInfoService.insert(formViewChangeInfoEntity);
            if (BeanUtil.isNotEmpty(formViewPubChangeDto)) {
                FormViewPubEntity formViewPub = formViewPubChangeDto.getViewPubInfo();
                if (BeanUtil.isNotEmpty(processCmd)) {
                    processCmd.setBusinessKey(formViewChangeInfoEntity.getId());
                    processCmd.setData(JSON.toJSONString(formViewPub));
                    processCmd.setAppId(baseUserInfo.getAppId());
                    bpmProcessInstanceService.startProcessInstance(processCmd);
                }
            } else {
                //更新日志主表信息
                formViewChangeInfoEntity.setId(formViewPubChangeDto.getLogId());
                formViewChangeInfoEntity.setOperationStatus(FormConstant.CHANGE_OPERATION_APPROVAL);
                formViewChangeInfoEntity.setRemark(formViewPubChangeDto.getRemark());
                formViewChangeInfoEntity.setChangeCount(String.valueOf(detailList.size()));
                //更新数据
                formViewChangeInfoService.updateById(formViewChangeInfoEntity);
            }

            //新增属性存储，状态为临时状态且没有关联视图
            if (addFormAttributePubList.size() > 0) {
                formAttributePubService.insertBatch(addFormAttributePubList);
            }

            //变更明细补充字段
            for (FormViewChangeInfoDetailEntity temp : detailList) {
                temp.setChangeInfoId(formViewChangeInfoEntity.getId());
            }
            //保存变更明细数据
            formViewChangeInfoDetailService.insertBatch(detailList);
        }
        return RestResponse.success("保存成功");
    }


    /**
     * 根据变更主表id获取视图信息
     *
     * @param logId
     * @return
     */
    @Override
    public FormViewPubChangeDto getViewPubChangeDtoById(String logId) {
        //空值判断
        if (StringUtil.isEmpty(logId)) {
            return null;
        }
        FormViewPubChangeDto formViewPubChangeDto = new FormViewPubChangeDto();
        //数据查询
        FormViewChangeInfoEntity formViewChangeInfoEntity = formViewChangeInfoService.getById(logId);
        if (BeanUtil.isEmpty(formViewChangeInfoEntity)) {
            log.error("找不到对应的变更记录");
            return formViewPubChangeDto;
        }
        //查询视图信息,根据业务id
        FormViewPubEntity formViewPubEntity = formViewPubService.getById(formViewChangeInfoEntity.getLinkId());
        if (BeanUtil.isEmpty(formViewPubEntity)) {
            log.error("[" + formViewChangeInfoEntity.getLinkId() + "],找不到相应的视图信息");
            return formViewPubChangeDto;
        }

        //定义 变更前的视图属性信息,key为视图id，value为属性信息
        Map<String, FormAttributePubEntity> formAttributePubMap = new HashMap<String, FormAttributePubEntity>();
        //查询视图属性信息
        List<FormAttributePubEntity> formAttributePubList = formAttributePubService.getValidListByViewId(formViewPubEntity.getId());
        if (BeanUtil.isNotEmpty(formAttributePubList)) {
            formAttributePubMap = formAttributePubList.stream().collect(Collectors.toMap(FormAttributePubEntity::getId, item -> item));
        }

        //定义新增的属性id集合
        List<String> addAttributeIds = new ArrayList<>();
        /**
         * 查询变更明细
         */
        List<FormViewChangeInfoDetailEntity> viewChangeInfoDetailList = formViewChangeInfoDetailService.getListByChangeId(logId);
        if (BeanUtil.isNotEmpty(viewChangeInfoDetailList)) {
            for (FormViewChangeInfoDetailEntity temp : viewChangeInfoDetailList) {
                //获取变更分类
                String type = temp.getType();
                FormConstant.ChangeOperationEnum changeOperationEnum = FormConstant.ChangeOperationEnum.parse(type);
                switch (changeOperationEnum) {
                    case A:
                        /**
                         *   因为只能新增属性，故可以不做变更明细判断
                         *   判断当前属性是否落得，兼容审批通过查看明细
                         *   如果当前新增还在审批中，则需要根据属性新增id集合查询新增的属性并添加至集合
                         */
                        if (!formAttributePubMap.containsKey(temp.getLinkId())) {
                            ListUtil.addUniqueValue(addAttributeIds, temp.getLinkId());
                        }
                        break;
                    case M:
                        if (CHANGE_VIEW_INFO.equals(temp.getLinkTable())) {
                            //再次确认一下视图基本信息主键 与变更明细表linkId
                            if (formViewPubEntity.getId().equals(temp.getLinkId())) {
                                //设置最新值
                                BeanUtil.setProperty(formViewPubEntity, temp.getFieldCode(), temp.getNewValue());
                            }
                        } else if (CHANGE_ATTR_INFO.equals(temp.getLinkTable())) {
                            //属性表字段变更设置新值
                            if (formAttributePubMap.containsKey(temp.getLinkId())) {
                                //属性更新对象
                                FormAttributePubEntity updateFormAttributePub = formAttributePubMap.get(temp.getLinkId());
                                BeanUtil.setProperty(updateFormAttributePub, temp.getFieldCode(), temp.getNewValue());
                                //反填更新后的属性对象至map中
                                formAttributePubMap.put(temp.getLinkId(), updateFormAttributePub);
                            }
                        } else {
                            log.debug("不处理");
                        }
                        break;
                    case D:
                        /**
                         * 因为只能删除属性，故可以不做变更明细判断
                         * 审批中 审批不通过的变更明细记录，需要从属性集合中移除
                         */
                        if (FormConstant.CHANGE_OPERATION_APPROVAL.equals(formViewChangeInfoEntity.getOperationStatus())
                                || FormConstant.CHANGE_OPERATION_NOAPPROVE.equals(formViewChangeInfoEntity.getOperationStatus())
                        ) {
                            //删除的属性，属性列表不显示
                            if (formAttributePubMap.containsKey(temp.getLinkId())) {
                                formAttributePubMap.remove(temp.getLinkId());
                            }
                        }
                        System.out.println("删除");
                        break;
                    default:
                        log.debug("不处理");
                        break;
                }
            }
        }
        //定义所有的属性集合
        List<FormAttributePubEntity> allAttributePubList = new ArrayList<>();
        for (FormAttributePubEntity temp : formAttributePubMap.values()) {
            allAttributePubList.add(temp);
        }

        //查询变更新增的属性
        if (addAttributeIds.size() > 0) {
            List<FormAttributePubEntity> addAttributePubList = formAttributePubService.getBatchByIds(addAttributeIds);
            //新增属性添加至集合
            allAttributePubList.addAll(addAttributePubList);
        }
        //是否的字段
        List<String> radioFields = new ArrayList<>();
        radioFields.add("queryItem");
        radioFields.add("listView");
        radioFields.add("isPrimaryKey");
        radioFields.add("canNull");
        radioFields.add("isOnly");
        radioFields.add("openSimilar");
        radioFields.add("editView");
        radioFields.add("codeUse");

        List<FormViewChangeInfoDetailVo> showLogDetails = new ArrayList<>();
        //处理变更明细的显示
        if (BeanUtil.isNotEmpty(viewChangeInfoDetailList)) {
            FormViewChangeInfoDetailVo showDetailVo = null;
            for (FormViewChangeInfoDetailEntity temp : viewChangeInfoDetailList) {
                showDetailVo = new FormViewChangeInfoDetailVo();
                BeanUtil.copyProperties(showDetailVo, temp);
                String showDetailOldName =temp.getOldValue();
                String showDetailNewName =temp.getNewValue();
                /**
                 * 特殊字段处理显示
                 */
                if (radioFields.contains(temp.getFieldCode())) {
                    if (StringUtil.isNotEmpty(temp.getOldValue())) {
                        showDetailOldName = "1".equals(temp.getOldValue()) ? "是" : "否";
                    }
                    if (StringUtil.isNotEmpty(temp.getNewValue())) {
                        showDetailNewName = "1".equals(temp.getNewValue()) ? "是" : "否";
                    }
                } else if (CHANGE_ATTR_INFO.equals(temp.getLinkTable()) && "regularRule".equals(temp.getFieldCode())){
                    //校验规则字段回显处理
                    showDetailOldName = this.getRegularRuleShowName(temp.getOldValue());
                    showDetailNewName = this.getRegularRuleShowName(temp.getNewValue());

                }else if (CHANGE_ATTR_INFO.equals(temp.getLinkTable()) && "desensitizationRule".equals(temp.getFieldCode())){
                    //脱敏规则字段回显处理
                    showDetailOldName = this.getDesensitizationRuleShowName(temp.getOldValue());
                    showDetailNewName = this.getDesensitizationRuleShowName(temp.getNewValue());

                } else if (CHANGE_ATTR_INFO.equals(temp.getLinkTable()) && "referenceType".equals(temp.getFieldCode())){
                    //参考数据类型回显处理
                    showDetailOldName = this.getReferenceTypeShowName(temp.getOldValue());
                    showDetailNewName = this.getReferenceTypeShowName(temp.getNewValue());

                } else if (CHANGE_ATTR_INFO.equals(temp.getLinkTable()) && "datasource".equals(temp.getFieldCode())){
                    //数据源字段回显处理
                    showDetailOldName = this.getDatasourceShowName(temp.getOldValue());
                    showDetailNewName = this.getDatasourceShowName(temp.getNewValue());

                }else if (CHANGE_ATTR_INFO.equals(temp.getLinkTable()) && "referenceData".equals(temp.getFieldCode())){
                    //参考数据的回显需要先分析参考类型
                    if(formAttributePubMap.containsKey(temp.getLinkId())){
                        //获取当前属性类型
                        FormAttributePubEntity currAttributePubEntity = formAttributePubMap.get(temp.getLinkId());
                        if(BeanUtil.isNotEmpty(currAttributePubEntity) && StringUtil.isNotEmpty(currAttributePubEntity.getReferenceType())){
                            if ("codeRule".equals(currAttributePubEntity.getReferenceType())) {
                                //编码规则回显
                                showDetailOldName = this.getCodeRuleShowName(temp.getOldValue());
                                showDetailNewName = this.getCodeRuleShowName(temp.getNewValue());

                            } else if ("view".equals(currAttributePubEntity.getReferenceType())) {
                                //视图数据回显
                                showDetailOldName = this.getViewShowName(temp.getOldValue());
                                showDetailNewName = this.getViewShowName(temp.getNewValue());
                            }
                        }
                    }
                }else {
                    //其它不处理
                }
                showDetailVo.setShowDetailOldName(showDetailOldName);
                showDetailVo.setShowDetailNewName(showDetailNewName);
                showLogDetails.add(showDetailVo);
            }
        }
        formViewPubChangeDto.setLogId(formViewChangeInfoEntity.getId());
        formViewPubChangeDto.setRemark(formViewChangeInfoEntity.getRemark());
        //设置视图基本信息
        formViewPubChangeDto.setViewPubInfo(formViewPubEntity);
        formViewPubChangeDto.setAttributePubList(allAttributePubList); //填充属性信息
        formViewPubChangeDto.setShowLogDetails(showLogDetails);
        return formViewPubChangeDto;
    }

    //获取校验规则回显明细
    private String getRegularRuleShowName(String fieldValue) {
        if(StringUtil.isNotEmpty(fieldValue)){
            ToolValidateConfigEntity toolValidateConfig = mdmToolValidateConfigService.queryById(fieldValue);
            if (BeanUtil.isNotEmpty(toolValidateConfig)) {
                return toolValidateConfig.getName();
            }
        }
        return fieldValue;
    }

    //获取脱敏规则回显明细
    private String getDesensitizationRuleShowName(String fieldValue) {
        if(StringUtil.isNotEmpty(fieldValue)){
            ToolDesensitizationRulesEntity toolDesensitizationRulesEntity = mdmToolDesensitizationRulesService.queryDesensitizationRulesById(fieldValue);
            if (BeanUtil.isNotEmpty(toolDesensitizationRulesEntity)) {
                return toolDesensitizationRulesEntity.getDesensitizationName();
            }
        }
        return fieldValue;
    }

    //获取编码规则回显明细
    private String getCodeRuleShowName(String fieldValue) {
        if(StringUtil.isNotEmpty(fieldValue)){
            ToolsCodeRulesEntity toolsCodeRulesEntity = codeRuleService.queryToolsCodeRuleById(fieldValue);
            if (BeanUtil.isNotEmpty(toolsCodeRulesEntity)) {
                return toolsCodeRulesEntity.getName();
            }
        }
        return fieldValue;
    }

    //获取视图数据回显
    private String getViewShowName(String fieldValue) {
        if(StringUtil.isNotEmpty(fieldValue)){
            FormViewEntity formViewEntity = formViewService.getById(fieldValue);
            if (BeanUtil.isNotEmpty(formViewEntity)) {
                return formViewEntity.getName();
            }
        }
        return fieldValue;
    }


    //参考类型数据回显处理
    private String getReferenceTypeShowName(String fieldValue) {
        if(StringUtil.isNotEmpty(fieldValue)){
            if ("defaultSysValue".equals(fieldValue)) {
                return "当前系统默认值";
            } else if ("codeRule".equals(fieldValue)) {
                return "编码规则";
            } else if ("view".equals(fieldValue)) {
                return "视图";
            } else if ("dict".equals(fieldValue)) {
                return "业务字典";
            }else {
                return "无";
            }
        }
        return fieldValue;
    }

    //获取数据源名称回显
    private String getDatasourceShowName(String fieldValue) {
        if(StringUtil.isNotEmpty(fieldValue)){
            DataBaseEntity dataBaseEntity = ucDataBaseService.queryById(fieldValue);
            if (BeanUtil.isNotEmpty(dataBaseEntity)) {
                return dataBaseEntity.getJdbcName();
            }
        }
        return fieldValue;
    }

    /**
     * 反对视图变更，新增的属性数据回滚
     *
     * @param changeId
     * @return
     */
    @Override
    public RestResponse opposeViewChange(String changeId) {
        //数据查询
        FormViewChangeInfoEntity formViewChangeInfoEntity = formViewChangeInfoService.getById(changeId);
        if (BeanUtil.isEmpty(formViewChangeInfoEntity)) {
            return RestResponse.error("[" + changeId + "]找不到关联的变更日志记录，请检查请求参数");
        }
        //已经审批通过的数据，不能更新
        if (FormConstant.CHANGE_OPERATION_SUCCESS.equals(formViewChangeInfoEntity.getOperationStatus())) {
            return RestResponse.error("[" + changeId + "]当前业务数据状态已经处于审核通过状态，不允许执行反对事件");
        }
        if (FormConstant.CHANGE_OPERATION_CANCEL.equals(formViewChangeInfoEntity.getOperationStatus())) {
            return RestResponse.error("[" + changeId + "]删除状态的业务数据，不允许重复执行删除事件");
        }

        //定义新增的属性id集合
        List<String> addAttributeIds = new ArrayList<>();
        //查询变更明细数据
        List<FormViewChangeInfoDetailEntity> viewChangeInfoDetailList = formViewChangeInfoDetailService.getListByChangeId(changeId);
        if (BeanUtil.isNotEmpty(viewChangeInfoDetailList)) {
            /**
             * 新增的属性记录需要回滚删除
             */
            for (FormViewChangeInfoDetailEntity detail : viewChangeInfoDetailList) {
                //变更类型为新增时，需要删除属性表添加的记录
                if (FormConstant.ChangeOperationEnum.A.name().equals(detail.getType())) {
                    ListUtil.addUniqueValue(addAttributeIds, detail.getLinkId());
                }
            }
        }
        if (addAttributeIds.size() > 0) {
            formAttributePubService.deleteBatchIds(addAttributeIds);
        }
        //设置状态
        FormViewPubEntity formViewPubBean = formViewPubService.getById(formViewChangeInfoEntity.getLinkId());

        FormViewPubEntity updateFormViewPubEntity = new FormViewPubEntity();
        updateFormViewPubEntity.setId(formViewChangeInfoEntity.getLinkId());
        if(StringUtil.isNotEmpty(formViewPubBean.getBizStatus())){
            if("50".equals(formViewPubBean.getBizStatus()) ||"35".equals(formViewPubBean.getBizStatus()) ||"45".equals(formViewPubBean.getBizStatus())){
                updateFormViewPubEntity.setBizStatus("45");
            }else {
                updateFormViewPubEntity.setBizStatus("40");
            }
        }else {
            updateFormViewPubEntity.setBizStatus("40");
        }
        formViewPubService.updateById(updateFormViewPubEntity);


        formViewChangeInfoEntity.setOperationStatus(FormConstant.CHANGE_OPERATION_CANCEL);
        formViewChangeInfoService.updateById(formViewChangeInfoEntity); //更新变更主表
        return RestResponse.success("执行成功");
    }

    /**
     * 视图变更 审核通过处理
     *
     * @param changeId
     * @return
     */
    @Override
    public RestResponse approvalViewChange(String changeId) {
        //数据查询
        FormViewChangeInfoEntity viewChangeInfoEntity = formViewChangeInfoService.getById(changeId);
        if (BeanUtil.isEmpty(viewChangeInfoEntity)) {
            return RestResponse.error("[" + changeId + "]找不到关联的变更日志记录，请检查请求参数");
        }
        //已经审批通过的数据，不能更新
        if (FormConstant.CHANGE_OPERATION_SUCCESS.equals(viewChangeInfoEntity.getOperationStatus())) {
            return RestResponse.error("[" + changeId + "]当前业务数据状态已经处于审核通过状态，不允许重复执行同意事件");
        }
        if (FormConstant.CHANGE_OPERATION_CANCEL.equals(viewChangeInfoEntity.getOperationStatus())) {
            return RestResponse.error("[" + changeId + "]删除状态的业务数据，不允许执行同意事件");
        }
        //查询变更明细数据
        List<FormViewChangeInfoDetailEntity> viewChangeInfoDetailList = formViewChangeInfoDetailService.getListByChangeId(changeId);
        if (BeanUtil.isNotEmpty(viewChangeInfoDetailList)) {
            //视图主键id
            List<String> viewIdList = new ArrayList<String>();
            //属性主键id
            List<String> attributeIdList = new ArrayList<String>();
            for (FormViewChangeInfoDetailEntity detail : viewChangeInfoDetailList) {
                if (CHANGE_VIEW_INFO.equals(detail.getLinkTable())) {
                    //视图集合
                    ListUtil.addUniqueValue(viewIdList, detail.getLinkId());
                } else if (CHANGE_ATTR_INFO.equals(detail.getLinkTable())) {
                    //属性集合
                    ListUtil.addUniqueValue(attributeIdList, detail.getLinkId());
                }
            }
            //定义视图变更中 需要更新的视图信息 key值为主键id  value 为对应的视图信息
            Map<String, FormViewPubEntity> updateViewPubMap = new HashMap<String, FormViewPubEntity>();

            //定义视图变更中 需要更新的属性信息 key值为主键id  value 为对应的属性信息
            Map<String, FormAttributePubEntity> updateAttributePubMap = new HashMap<String, FormAttributePubEntity>();
            List<String> allViewIds = new ArrayList<>();
            if (viewIdList.size() > 0) {
                allViewIds.addAll(viewIdList);
                //查询视图属性信息
                List<FormViewPubEntity> viewPubList = formViewPubService.getBatchByIds(viewIdList);
                if (BeanUtil.isNotEmpty(viewPubList)) {
                    updateViewPubMap = viewPubList.stream().collect(Collectors.toMap(FormViewPubEntity::getId, item -> item));
                }
            }
            if (attributeIdList.size() > 0) {
                //查询视图属性信息
                List<FormAttributePubEntity> formAttributePubList = formAttributePubService.getBatchByIds(attributeIdList);
                if (BeanUtil.isNotEmpty(formAttributePubList)) {
                    //只有属性变更时，收集viewId
                    List<String> attrViewIds = formAttributePubList.stream().map(FormAttributePubEntity::getViewId).distinct().collect(Collectors.toList());
                    allViewIds.addAll(attrViewIds);
                    updateAttributePubMap = formAttributePubList.stream().collect(Collectors.toMap(FormAttributePubEntity::getId, item -> item));
                }
            }
            if(allViewIds.size()>0){
                try{
                    //先清除缓存
                    formViewPubService.delByViewIds(allViewIds);
                    formAttributePubService.delAttrCacheByViewIds(allViewIds);
                }catch (Exception e){
                    log.error("清除缓存出错");
                    e.printStackTrace();
                }
            }

            for (FormViewChangeInfoDetailEntity temp : viewChangeInfoDetailList) {
                //获取变更分类
                String type = temp.getType();
                FormConstant.ChangeOperationEnum changeOperationEnum = FormConstant.ChangeOperationEnum.parse(type);
                switch (changeOperationEnum) {
                    case A:
                        /**
                         *  新增的属性，关联视图id 状态正常
                         */
                        if (updateAttributePubMap.containsKey(temp.getLinkId())) {
                            FormAttributePubEntity addAttributePubEntity = updateAttributePubMap.get(temp.getLinkId());
                            addAttributePubEntity.setViewId(viewChangeInfoEntity.getLinkId());
                            addAttributePubEntity.setStatus("1");
                            updateAttributePubMap.put(temp.getLinkId(), addAttributePubEntity); //反填数据
                        }
                        break;
                    case M:
                        if (CHANGE_VIEW_INFO.equals(temp.getLinkTable())) {
                            //处理更新的视图基本信息
                            if (updateViewPubMap.containsKey(temp.getLinkId())) {
                                FormViewPubEntity updateViewPubEntity = updateViewPubMap.get(temp.getLinkId());
                                //更新值
                                BeanUtil.setProperty(updateViewPubEntity, temp.getFieldCode(), temp.getNewValue());
                                updateViewPubMap.put(temp.getLinkId(), updateViewPubEntity);
                            }
                        } else if (CHANGE_ATTR_INFO.equals(temp.getLinkTable())) {
                            //处理更新的属性表字段
                            if (updateAttributePubMap.containsKey(temp.getLinkId())) {
                                FormAttributePubEntity updateAttributePubEntity = updateAttributePubMap.get(temp.getLinkId());
                                //更新值
                                BeanUtil.setProperty(updateAttributePubEntity, temp.getFieldCode(), temp.getNewValue());
                                //反填数据
                                updateAttributePubMap.put(temp.getLinkId(), updateAttributePubEntity);
                            }
                        } else {
                            log.debug("不处理");
                        }
                        break;
                    case D:
                        //删除做逻辑删除，状态设置为无效
                        if (updateAttributePubMap.containsKey(temp.getLinkId())) {
                            FormAttributePubEntity updateAttributePubEntity = updateAttributePubMap.get(temp.getLinkId());
                            updateAttributePubEntity.setStatus("0");
                            //反填数据
                            updateAttributePubMap.put(temp.getLinkId(), updateAttributePubEntity);
                        }
                        System.out.println("删除");
                        break;
                    default:
                        log.debug("不处理");
                        break;
                }
            }
            //更新视图基本信息
            if (updateViewPubMap.size() > 0) {
                formViewPubService.saveBatch(updateViewPubMap.values());
            }

            //更新属性表数据
            if (updateAttributePubMap.size() > 0) {
                formAttributePubService.saveBatch(updateAttributePubMap.values());
            }
        }

        //设置状态

        if(StringUtil.isEmpty(viewChangeInfoEntity.getLinkId())){
            return RestResponse.error("变更主表的linkId为空");
        }
        FormViewPubEntity formViewPubBean = formViewPubService.getById(viewChangeInfoEntity.getLinkId());

        FormViewPubEntity updateFormViewPubEntity = new FormViewPubEntity();
        updateFormViewPubEntity.setId(viewChangeInfoEntity.getLinkId());
        if(StringUtil.isNotEmpty(formViewPubBean.getBizStatus())){
            if("50".equals(formViewPubBean.getBizStatus()) ||"35".equals(formViewPubBean.getBizStatus()) ||"45".equals(formViewPubBean.getBizStatus())){
                updateFormViewPubEntity.setBizStatus("45");
            }else {
                updateFormViewPubEntity.setBizStatus("40");
            }
        }else {
            updateFormViewPubEntity.setBizStatus("40");
        }

        formViewPubService.updateById(updateFormViewPubEntity);
        //版本号加1
        FormDefinitionEntity formDefinitionEntity = new FormDefinitionEntity();
        formDefinitionEntity.setViewId(viewChangeInfoEntity.getLinkId());
        List<FormDefinitionEntity> list = formDefinitionService.getList(formDefinitionEntity);
        if(BeanUtil.isNotEmpty(list)&&list.size()>0){
            String oldVersion = list.get(0).getVersion();
            double newVersionDou = Double.parseDouble(oldVersion)+1;
            String newVersion = Double.toString(newVersionDou);
            FormDefinitionEntity newDeinitionEntity = new FormDefinitionEntity();
            newDeinitionEntity.setId(list.get(0).getId());
            newDeinitionEntity.setVersion(newVersion);
            formDefinitionService.updateById(newDeinitionEntity);
        }

        viewChangeInfoEntity.setOperationStatus(FormConstant.CHANGE_OPERATION_SUCCESS);
        formViewChangeInfoService.updateById(viewChangeInfoEntity); //更新变更主表状态
        return RestResponse.success("执行成功");
    }

    /**
     * 视图变更 对比字段配置
     *
     * @return
     */
    @Override
    public Map<String, List<ChangeField>> getViewChangeFieldConfig() {
        Map<String, List<ChangeField>> viewChangeFieldConfigMap = new HashMap<>();
        //定义视图基本信息变更字段
        List<ChangeField> viewChangeFields = new ArrayList<ChangeField>();
        viewChangeFields.add(new ChangeField("name", "标题"));
        viewChangeFields.add(new ChangeField("datasource", "数据源"));
        viewChangeFields.add(new ChangeField("linkTable", "所属表"));
        viewChangeFields.add(new ChangeField("idField", "ID字段"));
        viewChangeFields.add(new ChangeField("viewField", "显示字段"));
        viewChangeFields.add(new ChangeField("foreignKeyMapping", "外键映射"));
        viewChangeFields.add(new ChangeField("remark", "描述"));

        //定义属性变更字段
        List<ChangeField> attributeChangeFields = new ArrayList<ChangeField>();
        attributeChangeFields.add(new ChangeField("code", "编码"));
        attributeChangeFields.add(new ChangeField("name", "名称"));
        attributeChangeFields.add(new ChangeField("dataType", "数据类型"));
        attributeChangeFields.add(new ChangeField("dataLength", "数据长度"));
        attributeChangeFields.add(new ChangeField("dataAccuracy", "数据精度"));
        attributeChangeFields.add(new ChangeField("isPrimaryKey", "是否主键"));
        attributeChangeFields.add(new ChangeField("canNull", "是否可为空"));
        attributeChangeFields.add(new ChangeField("isOnly", "是否唯一"));

        attributeChangeFields.add(new ChangeField("queryItem", "查询条件"));
        attributeChangeFields.add(new ChangeField("listView", "列表显示"));
        attributeChangeFields.add(new ChangeField("openSimilar", "开启相似度"));
        attributeChangeFields.add(new ChangeField("editView", "编辑显示"));
        attributeChangeFields.add(new ChangeField("desensitizationRule", "脱敏规则"));
        attributeChangeFields.add(new ChangeField("regularRule", "校验规则"));
        attributeChangeFields.add(new ChangeField("referenceType", "参考类型"));
        attributeChangeFields.add(new ChangeField("referenceData", "参考数据"));
        attributeChangeFields.add(new ChangeField("viewSort", "显示顺序"));
        attributeChangeFields.add(new ChangeField("codeUse", "用于编码"));
        attributeChangeFields.add(new ChangeField("codeUseAlias", "用于编码的别名"));

        viewChangeFieldConfigMap.put(CHANGE_VIEW_INFO, viewChangeFields);
        viewChangeFieldConfigMap.put(CHANGE_ATTR_INFO, attributeChangeFields);
        return viewChangeFieldConfigMap;
    }
}
